
/**
 * @desc 小程序订阅功能
 * @param {Array} tmplIds 订阅列表
 * @returns {Promise} 返回promise
*/

//永久关闭订阅则代表点击了我不在接受此消息，再次订阅是无法弹起授权窗口的。普通关闭时可以再次弹起授权窗口
export const Subscribe = (tmplIds=[])=>{
	return new Promise((resolve,reject)=>{
		//判断是否为微信小程序，不是的不做订阅进行跳过
		let isWx=false;
		isWx=true;
		if(!isWx)resolve(1);
		// 判断基本库是否在2.8.3，低于的暂时不做订阅进行跳过
		let versionCan= compareVersion('2.8.3');
		if(versionCan === -1) reject(1);
		requestSubscribe(tmplIds,resolve,reject)
		
	})
}
//申请订阅功能
function requestSubscribe(tmplIds,resolve,reject){
	uni.requestSubscribeMessage({
		tmplIds,
		success:async res=>{
			//检查是否订阅
			let checkSubscribeBool= await checkSubscribeAll(tmplIds,res);
			if(checkSubscribeBool){
				console.log("用户订阅完成");
				resolve(1)
			}else{
				// 跳去检查永久关闭订阅还是普通关闭订阅
				guidSubscribeMessageAuthAfter(tmplIds,resolve,reject);
			}
		},
		fail:res=>{
			console.log('用户订阅失败',res);
			if(res.errCode==='20004'){
				guideOpenSubscribeMessage(tmplIds,resolve,reject)
			}
			return
		}
	})
}
//计算用户订阅消息的数量
function checkSubscribeAll(tmplIds,res){
	// 将accept的生成一个数组，判断申请的订阅消息是不是已经订阅消息的子集
	let arr=[];
	for(const key of Object.keys(res) ){
		if(res[key] === 'accept'){
			arr.push(key)
		}
	}
	if(arr.length === tmplIds.length){
		console.log('订阅完毕');
		return true
	}else{
		console.log('未订阅');
		return false
	}
}

//检查用户是否授权完毕（检查时永久关闭还是普通关闭）
function guidSubscribeMessageAuthAfter(tmplIds, resolve, reject){
	uni.getSetting({
		withSubscriptions:true,
		success:async res=>{
			let {
				authSetting = {},
				subscriptionsSetting:{mainSwitch=false,itemSettings = {} }={}
			}=res;
			if(Object.keys(itemSettings).length ===0){//普通关闭
				uni.showModal({
					title:'温馨提示',
					content:'同意订阅才能收到通知',
					confirmText:'重新订阅',
					cancelText:'我在想想',
					success: (res) => {
						if(res.confirm){
							requestSubscribe(tmplIds, resolve, reject);
						}
						else if(res.cancel){
							reject(2);
						}
					}
				})
			}else{//订阅成功或者永久关闭
				let checkSubscribeBool= await checkSubscribeAll(tmplIds,itemSettings);
				if( authSetting['scope.subscribeMessage'] || (mainSwitch > checkSubscribeBool)){
					console.log("用户手动开启同意了，订阅消息");
					resolve(1)
				}else{
					//失败，永久关闭
					guideOpenSubscribeMessage(tmplIds, resolve, reject);
				}
			}
		},
		
	})
}
//引导用户重新授权（永久关闭的方法）
function guideOpenSubscribeMessage(tmplIds, resolve, reject){
	console.log(resolve, reject, 'guideOpenSubscribeMessage');
	uni.showModal({
		title:'温馨提示',
		content:'检测到您没有开启全部订阅消息的权限，是否去设置？',
		success: (res) => {
			if(res.confirm){
				uni.openSetting({
					success: () => {
						//在检查是否全部订阅完毕
						 guidSubscribeMessageAuthAfter(tmplIds, resolve, reject);
					}
					                    
				})
			}else if(res.cancel){
				uni.showModal({
					title:'温馨提示',
					content:'同意订阅才能收到通知',
					showCancel:false,
					confirmText:'我知道了'
				})
				reject(2)
			}
		}
		
	})
}
//比较版本号
function compareVersion(v2){
	let { SDKVersion: v1 } = uni.getSystemInfoSync();
		v1 = v1.split(".");
	    v2 = v2.split(".");
		const len = Math.max(v1.length, v2.length);
		while(v1.length <len){
			v1.push('0')
		}
		while(v2.length <len){
			v2.push('0')
		}
		for(let i =0;i<len;i++){
			const num1 = parseInt(v1[i])
			const num2 = parseInt(v2[i])
			
			if(num1 >num2){
				return 1
			}else if(num1 <num2){
				return -1
			}
		}
		
	return 0;	
}